﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Complaint.Common
{
    public class FileUploader
    {
        public static string SaveProofFile(HttpFileCollectionBase files)
        {
            string savedFileName = null;
            //save the user uploaded proof file
            foreach (string file in files)
            {
                var hpf = files[file];
                if (hpf.ContentLength == 0)
                    continue;

                //file validation such as size and type
                CheckFileSize(hpf);
                CheckFileType(hpf);

                savedFileName = MakeUnique(hpf.FileName).FullName;
                hpf.SaveAs(savedFileName);
                break;
            }
            return savedFileName;
        }

        private static void CheckFileType(HttpPostedFileBase hpf)
        {
            IEnumerable<string> fileTypes = ConfigHelper.GetConfigValue("AllowedFileTypes").Split(new[] {','});
            if (!fileTypes.Any(t => hpf.ContentType.Contains(t)))
            {
                throw new InvalidOperationException("Invalid upload file type.");
            }
        }

        private static void CheckFileSize(HttpPostedFileBase hpf)
        {
            if (hpf.ContentLength > ConfigHelper.GetConfigValueAsInt("MaxFileSize"))
                throw new ArgumentOutOfRangeException("files", "Upload file size exceeds maximum allowed file size.");
        }

        private static FileInfo MakeUnique(string filename)
        {
            var dir = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    ConfigHelper.GetConfigValue("ProofFileRelativePath")
                    );
            var fileName = Path.GetFileNameWithoutExtension(filename);
            var fileExt = Path.GetExtension(filename);
            var path = Path.Combine(dir, Path.GetFileName(filename));

            for (var i = 1; ; ++i)
            {
                if (!File.Exists(path))
                    return new FileInfo(path);

                path = Path.Combine(dir, fileName + "-" + i + fileExt);
            }
        }

    }
}
